package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class IndexController {

    @Resource
    private ProductFeignClient productFeignClient;
    // static /webapp/index.html
    // templates  WEB-INF/index/index.html
    //首页
    @GetMapping("/")
    public String index(Model model){
        List<Map> listMap = new ArrayList<>();

        List<BaseCategoryView> baseCategoryViewList = productFeignClient.getBaseCategoryViewAll();

        //根据一级分类筛出的map
        Map<Long, List<BaseCategoryView>> baseCategoryViewListMap =
                baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //1、前60数据(一级分类)一个map
        baseCategoryViewListMap.forEach((k,v)->{
            Map category1Map = new HashMap<>();
            category1Map.put("index",k);
            category1Map.put("categoryId",k);
            category1Map.put("categoryName",v.get(0).getCategory1Name());//获取一级名称，list中下标0的数据中get名称

            Map<Long, List<BaseCategoryView>> baseCategoryView2ListMap =
                    baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));

            List<Object> list2 = new ArrayList<>();
            baseCategoryView2ListMap.forEach((k2,v2) ->{
                Map category2Map = new HashMap<>();
                category2Map.put("categoryId",k2);
                category2Map.put("categoryName",v2.get(0).getCategory2Name());
                //三级分类
                List<Map> list3 = new ArrayList<>();
                v2.forEach(baseCategoryView -> {
                    Map category3Map = new HashMap<>();
                    category3Map.put("categoryId",baseCategoryView.getCategory3Id());
                    category3Map.put("categoryName",baseCategoryView.getCategory3Name());
                    list3.add(category3Map);
                });
                category2Map.put("categoryChild",list3);
                list2.add(category2Map);

            });
            category1Map.put("categoryChild",list2);
            listMap.add(category1Map);


        });
        model.addAttribute("list",listMap);

        return "index/index";
    }
}
